//
//  ViewController.m
//  FMDB_Test_Demo
//
//  Created by 故乡的云  on 2017/4/8.
//  Copyright © 2017年 故乡的云 . All rights reserved.
//

#import "ViewController.h"
#import "TLChengYu.h"
#import "TLFMDB.h"
#import "TLAddItemWindow.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property(nonatomic, weak) UITableView *tableView;
@property(nonatomic, weak) UISearchBar *searchBar;
@property(nonatomic, strong) NSMutableArray *items;
@property(nonatomic, assign) bool shouldEdit;
@end

@implementation ViewController

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.tableView.autoresizingMask = YES;
    [self setNav];
}

#pragma mark - 设置导航栏，添加事件处理
-(void)setNav {
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [addBtn addTarget:self action:@selector(addItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    
    UIButton *editBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    [editBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [editBtn addTarget:self action:@selector(editItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.navigationItem.titleView = searchBar;
    searchBar.delegate = self;
    searchBar.placeholder = @"请输入关键字,不多字，不隔字";
    self.searchBar = searchBar;
}

- (void)addItem:(UIButton *)btn {
    [self searchBarCancelButtonClicked:self.searchBar];
    __weak ViewController *weakSelf = self;
    [TLAddItemWindow showWithItem:nil doneButtonClick:^(TLChengYu * _Nonnull item) {
        [TLFMDB insertModel:item];
        [weakSelf.items addObject:item];
        
        [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[weakSelf.items indexOfObject:item] inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
    }];
}

- (void)editItem:(UIButton *)btn {
    [self searchBarCancelButtonClicked:self.searchBar];
    btn.selected = !btn.isSelected;
    self.shouldEdit = btn.isSelected;
    if (btn.isSelected) {
        [btn setTitle:@"完成" forState:UIControlStateNormal];
    }else {
        [btn setTitle:@"编辑" forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}

- (void)reloadTableView {
    
    self.items = nil;
    [self.tableView reloadData];
}

#pragma mark - table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.detailTextLabel.textColor = [UIColor orangeColor];
    };
    TLChengYu *cy = self.items[indexPath.row];
    cell.textLabel.text = cy.name;
    cell.detailTextLabel.text = cy.pinYin;
    return cell;
}

#pragma mark - table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    if (!self.shouldEdit) return;
    
    // 弹出编辑框
    TLChengYu *__block cy = self.items[indexPath.row];
    __weak ViewController *weakSelf = self;
    [TLAddItemWindow showWithItem:cy doneButtonClick:^(TLChengYu * _Nonnull item) {
        [TLFMDB updateWithModel:cy toNewMOdel:item];
        weakSelf.items[indexPath.row] = item;
        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.shouldEdit;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        TLChengYu *cy = self.items[indexPath.row];
        [TLFMDB deleteDataWithCondition:[NSString stringWithFormat:@"name = \'%@\'",cy.name]];
        [self.items removeObject:cy];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
//        [self reloadTableView];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (self.shouldEdit) {
        return @"       提示: 点击词条进入编辑，向左滑动删除词条";
    }
    return nil;
}

#pragma mark - search bar delegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    [self searchSetUp:searchBar];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self searchSetUp:searchBar];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self searchSetUp:searchBar];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    [self reloadTableView];
    [searchBar resignFirstResponder];
}

//／ 查询处理
- (void)searchSetUp:(UISearchBar *)searchBar {
    self.items = [NSMutableArray arrayWithArray:[TLFMDB queryData:[NSString stringWithFormat:@" name Like \'%%%@%%\' or name Like \'%%%@\' or name Like \'%@%%\'",searchBar.text,searchBar.text,searchBar.text]]];
    [self.tableView reloadData];
}

#pragma mark - proterties
- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView = tableView;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:tableView];
    }

    return _tableView;
}

- (NSMutableArray *)items {
    if (!_items) {
        
        // 从数据库读取数据
        _items = [NSMutableArray arrayWithArray:[TLFMDB queryData:nil]];
        if (_items.count) return _items;
        
        // 数据库没有数据，加载默认数据
        NSString *path = [[NSBundle mainBundle] pathForResource:@"chengyu.plist" ofType:nil];
        NSArray *tempArr = [NSMutableArray arrayWithContentsOfFile:path];
        _items = [NSMutableArray array];
        for (NSDictionary *dict in tempArr) {
            TLChengYu *cy = [TLChengYu chengYuWithDict:dict];
            [_items addObject:cy];
            // 写入数据库
            [TLFMDB insertModel:cy];
        }
    }
    
    return _items;
}
@end
